package logic

import (
	"context"
	"strings"

	"mall/common/enumx"
	"mall/common/errorx"
	"mall/common/modelx"
	"mall/common/mqueuex"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetMemberAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetMemberAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetMemberAuthLogic {
	return &BackendGetMemberAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetMemberAuthLogic) BackendGetMemberAuth(in *user.BackendGetMemberAuthReq) (*user.BackendGetMemberAuthResp, error) {
	if len(in.AuthType) == 0 || len(in.MemberIds) == 0 {
		return nil, errorx.Status(errorx.ERROR_USER_AUTH_PARAM_INVALID, "")
	}

	// 查询用户是否存在
	filterMap := make(map[string]map[string][]interface{})
	switch in.AuthType {
	case mqueuex.UserAuthTypeWxMini:
		filterMap[model.UserAuthColumns.PlatformID] = map[string][]interface{}{
			"equalTo": []interface{}{enumx.ThirdPartyPlatformWechatMini},
		}
		filterMap[model.UserAuthColumns.UserID] = map[string][]interface{}{
			"in": modelx.UniqueValues(strings.Split(in.MemberIds, ","), 64),
		}
	}
	selectCols := []string{
		model.UserAuthColumns.UserAuthID,
		model.UserAuthColumns.UserID,
		model.UserAuthColumns.Nickname,
		model.UserAuthColumns.Avatar,
		model.UserAuthColumns.Openid,
		model.UserAuthColumns.Status,
	}

	userAuthList, _, err := l.svcCtx.User.GetAuthList(l.ctx, model.M{
		"select": strings.Join(selectCols, ","),
	}, -1, filterMap)
	if err != nil {
		return nil, err
	}

	count := len(userAuthList)
	if count == 0 {
		return &user.BackendGetMemberAuthResp{}, nil
	}

	var memberAuths []*user.UserAuth
	for _, userAuth := range userAuthList {
		memberAuths = append(memberAuths, &user.UserAuth{
			Id:         int64(userAuth.UserAuthID),
			UserId:     int64(userAuth.UserID),
			Nickname:   userAuth.Nickname,
			Avatar:     userAuth.Avatar,
			AuthKey:    userAuth.Openid,
			Authorized: int32(userAuth.Status),
		})
	}

	return &user.BackendGetMemberAuthResp{
		MemberAuth: memberAuths,
	}, nil
}
